import { useUserStore } from '@/stores/user'

// 不需要登录就可以访问的页面
const publicPages = [
  '/pages/login/login'
]

// 需要特定权限才能访问的页面
const permissionPages = {
  '/pages/device/device': ['device:view']
}

/**
 * 检查页面访问权限
 * @param {Object} options uni.navigateTo 等路由方法的参数对象
 * @returns {Promise} 返回是否可以访问
 */
export const checkPermission = (options) => {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore()
    
    // 获取目标页面路径
    const targetPage = options.url.split('?')[0]
    
    // 如果是公开页面，直接放行
    if (publicPages.includes(targetPage)) {
      resolve(true)
      return
    }
    
    // 检查是否登录
    if (!userStore.isLoggedIn) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }, 1500)
      
      reject(new Error('未登录'))
      return
    }
    
    // 检查页面权限
    const requiredPermissions = permissionPages[targetPage]
    if (requiredPermissions) {
      const hasPermission = requiredPermissions.every(permission => 
        userStore.hasPermission(permission)
      )
      
      if (!hasPermission) {
        uni.showToast({
          title: '没有访问权限',
          icon: 'none'
        })
        reject(new Error('无权限'))
        return
      }
    }
    
    resolve(true)
  })
}

// 重写路由方法
const routeMethods = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']

routeMethods.forEach(method => {
  const original = uni[method]
  uni[method] = async (options) => {
    try {
      await checkPermission(options)
      return original.call(uni, options)
    } catch (error) {
      return Promise.reject(error)
    }
  }
})

/**
 * 添加请求拦截器，自动添加token
 */
const originalRequest = uni.request
uni.request = (options = {}) => {
  const userStore = useUserStore()
  
  // 克隆原始配置
  const config = {
    ...options,
    header: {
      ...options.header
    }
  }
  
  // 添加token
  if (userStore.token) {
    config.header.Authorization = `Bearer ${userStore.token}`
  }
  
  // 发起请求
  return new Promise((resolve, reject) => {
    originalRequest({
      ...config,
      success: async (response) => {
        // 处理token过期
        if (response.statusCode === 401) {
          const refreshSuccess = await userStore.refreshToken()
          if (refreshSuccess) {
            // 重试当前请求
            try {
              const newResponse = await uni.request({
                ...options,
                header: {
                  ...options.header,
                  Authorization: `Bearer ${userStore.token}`
                }
              })
              resolve(newResponse)
            } catch (error) {
              reject(error)
            }
          } else {
            // token刷新失败，退出登录
            userStore.logout()
            uni.reLaunch({
              url: '/pages/login/login'
            })
            reject(new Error('登录已过期，请重新登录'))
          }
        } else {
          resolve(response)
        }
      },
      fail: reject
    })
  })
}

/**
 * 初始化检查登录状态
 */
export const initAuthCheck = () => {
  const userStore = useUserStore()
  const currentPage = getCurrentPages()[0]
  
  if (currentPage) {
    const currentPath = `/${currentPage.route}`
    
    // 如果当前页面不是公开页面，且未登录，则跳转到登录页
    if (!publicPages.includes(currentPath) && !userStore.isLoggedIn) {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }
  }
} 